import { ref } from 'vue';
import { defineStore } from 'pinia';
import { getGoodsCategoryTree as getCategoryTreeAPI } from '@/apis/goods-category';

export const useCategoryStore = defineStore('category', () => {
  const loadingCategoryTree = ref(false);
  const categoryTree = ref<API.goodsCategory.TreeSchema[]>();

  // 获取 - categoryTree
  const getCategoryTree = () => {
    // 优先从store里获取
    if (!categoryTree.value) updateCategoryTree();
    return categoryTree;
  };

  // 更新 - categoryTree
  const updateCategoryTree = async () => {
    // 减少请求次数
    if (loadingCategoryTree.value) return;
    loadingCategoryTree.value = true;
    try {
      const res = await getCategoryTreeAPI();
      categoryTree.value = res.data;
    } catch (error) {
      categoryTree.value = undefined;
      console.error('useCategoryStore - updateCategoryTree', error);
    }
    loadingCategoryTree.value = false;
    // return categoryTree;
  };

  return {
    loadingCategoryTree,
    categoryTree,
    getCategoryTree,
    updateCategoryTree
  };
});
